import { get as getVal, writable, type Writable } from "svelte/store";
import { object, string, number } from "yup";
import type { Paged } from "@util/http";


export enum EntryType {
  File = "file",
  Directory = "directory",
}

export type DatasetEntry = {
  id: number;
  updated_at: string | null;
  dataset_id: number;
  type: EntryType;
  dir: string;
  name: string;
  size: number;
  suffix: string | null;
  repo_url: string | null;
};

export type ListDatasetEntriesParam = {
  parent: string;
  page_no?: number;
  page_size?: number;
};

export type CreateDatasetEntryParam = {
  dataset_id: number;
  type: EntryType;
  dir: string;
  name: string;
};

export type UpdateDatasetEntryParam = {
  id: number;
  dir?: string;
  name?: string;
};

export type DeleteDatasetEntryParam = {
  id: number;
};

export const DatasetEntrySchema = object({
  id: number().required("数据集项id必填"),
  updated_at: string().optional(),
  dataset_id: number().required("数据集id必填"),
  type: string().required("数据集项类型必填"),
  dir: string().required("数据集项目录").max(128, "最多128个字"),
  name: string().required("数据集项名称必填").max(128, "最多128个字"),
  size: number(),
  suffix: string().optional(),
  repo_url: string().optional(),
});

export const CreateDatasetEntryParamSchema = DatasetEntrySchema.omit(["id", "updated_at", "size", "suffix"]);


export const DatasetEntryFactory = (dataset_id: number, type: EntryType, dir: string) => {
  return (): DatasetEntry =>  ({ id: null, updated_at:null, dataset_id, type, dir, name: "", size: 0, suffix:null, repo_url: null })
}

export const validDir = (val: string)  => {
  if (!val.startsWith("/")) {
    return `/${val}`
  }
  return  val
}

type DatasetEntryMap = {
  [k: string]: Writable<Paged<DatasetEntry>>;
};

const datasetEntryMap: DatasetEntryMap = {};

export const setDatasetEntrySubscribe = (datasetCode: string, o: Paged<DatasetEntry>) => {
  if (!datasetEntryMap[datasetCode]) {
    datasetEntryMap[datasetCode] = writable(o);
  }
  datasetEntryMap[datasetCode].set(o);
};

export const getDatasetEntrySubscribe = (datasetCode: string) => {
  let v = datasetEntryMap[datasetCode];
  if (!v) {
    datasetEntryMap[datasetCode] = v = writable();
  }
  return v;
};

export const hasDatasetEntrySubscribe = (datasetCode: string) => {
  return datasetEntryMap[datasetCode] && getVal(datasetEntryMap[datasetCode]) !== undefined;
};

export const getDatasetEntryInSubscribe = (datasetCode: string) => {
  return (entryId: number) => {
    const o = getDatasetEntrySubscribe(datasetCode);
    const {rows} = getVal(o);
    return rows.find(v => v.id === entryId)
  }
}